﻿Imports System.Data
Imports MySql.Data.MySqlClient
Public Class AProducts
    Dim connector As New MySqlConnection("server=127.0.0.1;database='commerce';user='root';password='';")
    Dim command As MySqlCommand
    Dim datareader As MySqlDataReader
    Private Sub AProducts_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.WindowState = FormWindowState.Maximized
        connector.Open()
        command = New MySqlCommand("select * from manufacturers", connector)
        datareader = command.ExecuteReader()
        While datareader.Read
            comManufacturer.Items.Add(datareader.Item("id"))
        End While
        datareader.Close()
        connector.Close()
    End Sub

    Private Sub comManufacturer_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comManufacturer.SelectedIndexChanged
        txtName.Enabled = True
    End Sub

    Private Sub txtName_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtName.TextChanged
        If Me.txtName.Text = "" Then
            Me.cmdSave.Enabled = False
        Else
            Me.cmdSave.Enabled = True
        End If
    End Sub

    Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
        connector.Open()
        command = New MySqlCommand("select * from products where name='" & Me.txtName.Text & "'", connector)
        datareader = command.ExecuteReader()
        Dim cont As Integer
        cont = 0
        While datareader.Read
            cont = cont + 1
        End While
        datareader.Close()
        If cont > 0 Then
            MsgBox(Me.txtName.Text & " already exists")
        Else
            command = New MySqlCommand("insert into products (name,manufacturer) values ('" & Me.txtName.Text & "','" & Me.comManufacturer.SelectedItem & "')", connector)
            command.ExecuteNonQuery()
            MsgBox(Me.txtName.Text & " added")
            txtName.Text = ""
        End If
        connector.Close()
    End Sub
End Class